package md.mru.frontend.convertors;

import md.mru.core.dtos.BaseDto;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ManagedBean
@ViewScoped
public class ObjectMappingConverter implements Converter, Serializable {

    private static final long serialVersionUID = 568470452950763846L;
    private Map<String, BaseDto> objectMap = new HashMap<>();

    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) throws ConverterException {
        return objectMap.get(value);
    }

    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) throws ConverterException {
        BaseDto object = (BaseDto) value;
        if (object == null) {
            return null;
        }
        return object.getId() != 0 ? object.getId() + object.getClass().getName() : null;
    }

    /**
     * Maps list objects with composed value from object id
     * and class name and adds it to the global map
     *
     * @param objects list of objects that goes to be mapped
     */
    public void mapObjectList(List<? extends BaseDto> objects) {
        if (objects == null) {
            return;
        }
        for (BaseDto object : objects) {
            objectMap.put(object.getId() + object.getClass().getName(), object);
        }
    }
}
